package com.tticar.invmanager.common.Interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.IPAddressUtil;
import com.tticar.invmanager.common.utils.MyBeanUtils;
import com.tticar.invmanager.entity.SysLogs;
import com.tticar.invmanager.service.ISysLogsService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 日志收集.
 */
public class LoggerInterceptor implements HandlerInterceptor {

    private ISysLogsService sysLogsService;

    private static final String LOGGER_SEND_TIME = "_send_time";
    private static final String LOGGER_ENTITY = "_logger_entity";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        SysLogs log = new SysLogs();
        String paramData = JSON.toJSONString(request.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue);
        log.setName(MySecurityUtils.currentUser() != null ? MySecurityUtils.currentUser().getNickname() : "");
        log.setIpAddr(IPAddressUtil.getIpAddr(request));
        log.setRmethod(request.getMethod());
        log.setRargs(paramData);
        log.setRuri(request.getRequestURI());
        log.setSessionId(request.getRequestedSessionId());
        log.setCtime(new Date());
        request.setAttribute(LOGGER_SEND_TIME, System.currentTimeMillis());
        request.setAttribute(LOGGER_ENTITY, log);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        SysLogs log = (SysLogs) request.getAttribute(LOGGER_ENTITY);
        log.setUtime(new Date());
        log.setRtime(log.getUtime().getTime() - log.getCtime().getTime());
        log.setStatuCode(response.getStatus() + "");

        if (sysLogsService == null) {
            sysLogsService = MyBeanUtils.getBean(ISysLogsService.class);
        }
//
        sysLogsService.insertLog(log);
    }

}
